<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="utf-8">
    <title>权限管理</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" th:href="@{/lib/layui-v2.5.5/css/layui.css}" media="all">
    <link rel="stylesheet" th:href="@{/css/public.css}" media="all">
    <link rel="stylesheet" th:href="@{/lib/bootstrap/css/bootstrap.css}" >
    <link rel="stylesheet" th:href="@{/lib/layui_ext/dtree/dtree.css}" >
    <link rel="stylesheet" th:href="@{/lib/layui_ext/dtree/font/dtreefont.css}" >
    <link rel="stylesheet" th:href="@{/lib/zTree/css/zTreeStyle/zTreeStyle.css}" >

</head>
<body>

<span th:replace="common_page::common"></span>

<div class="layuimini-container">
    <div class="layuimini-main">

        <fieldset class="table-search-fieldset">
            <div style="margin: 10px 10px 10px 10px">
                <form class="layui-form layui-form-pane" id="userSearchForm" action="">
                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">角色ID</label>
                            <div class="layui-input-inline">
                                <input type="text" name="roleId" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">角色名称</label>
                            <div class="layui-input-inline">
                                <input type="text" name="name" autocomplete="off" class="layui-input">
                            </div>
                        </div>
                        <div class="layui-inline">
                            <label class="layui-form-label">所属应用</label>
                            <div class="layui-input-inline">
                                <select id="selectApp" name="appCode" lay-search="">
                                    <option value="">请选择</option>
                                    <option th:each="aa : ${apps}" th:value="${aa.code}" th:text="${aa.code}+' '+${aa.name}">
                                </select>
                            </div>
                        </div>
                        <div class="layui-inline">
                            <button type="submit" class="layui-btn layui-btn-primary"  lay-submit lay-filter="data-search-btn"><i class="layui-icon"></i> 搜 索</button>
                            <button type="reset" class="layui-btn layui-btn-primary" id="data-reset-btn" > 重 置</button>
                        </div>
                    </div>
                </form>
            </div>
        </fieldset>

        <script type="text/html" id="toolbarDemo">
            <div class="layui-btn-container">
                <span th:each="tb : ${toolbarButtons}" th:utext="${tb}"></span>
            </div>
        </script>

        <table class="layui-hide" id="roleTable" lay-filter="roleTableFilter"></table>

        <script type="text/html" id="roleTableBar">
            <span th:each="btn : ${rowButtons}" th:utext="${btn}"></span>
        </script>

    </div>
</div>
<script th:src="@{/lib/layui-v2.5.5/layui.js}" charset="utf-8"></script>
<script th:src="@{/lib/jquery-3.4.1/jquery-3.4.1.min.js}" charset="utf-8"></script>
<script>
    layui.config({
        base: basePath+'/lib/layui_ext/dtree/' //配置 layui 第三方扩展组件存放的基础目录
    }).extend({
        dtree: 'dtree' //定义该组件模块名
    }).use(['form', 'table','tree','dtree'], function () {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table;
        var index;
        var tree = layui.tree;
        var loadding;
        var dtree = layui.dtree;
        var zTreeObj;
        var allTreeDataArray = new Array();
        var pushTreeDataArray = new Array();
        var savePermissionLoadding;

        $.fn.serializeJson=function(){
            var serializeObj={};
            var array=this.serializeArray();
            var str=this.serialize();
            $(array).each(function(){
                if(serializeObj[this.name]){
                    if($.isArray(serializeObj[this.name])){
                        serializeObj[this.name].push(this.value);
                    }else{
                        serializeObj[this.name]=[serializeObj[this.name],this.value];
                    }
                }else{
                    serializeObj[this.name]=this.value;
                }
            });
            return serializeObj;
        };

        function getFormParam()
        {
            var formParam = $("#userSearchForm").serializeJson();
            return formParam;
        }


        $("#data-reset-btn").click(function(){
            $("#userSearchForm")[0].reset();
            layui.form.render();
        });



        table.render({
            elem: '#roleTable',
            url: "[[@{/}]]role/list",
            method:'POST',
            where:getFormParam(),
            toolbar: '#toolbarDemo',
            defaultToolbar: ['filter',  {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            done:function(res, curr, count)
            {
            },
            cols: [
                [
                    {type: "checkbox", width: 50},
                    {field: 'roleId', width: 180, title: '角色ID'},
                    {field: 'name', width: 180, title: '角色名称'},
                    {field: 'appCode', width: 180, title: '应用编码'},
                    {field: 'appName', width: 180, title: '所属应用'},
                    {field: 'createAdminUsername', width: 180, title: '创建人'},
                    {field: 'createDate', width: 180, title: '创建时间'},
                    {field: 'updateAdminUsername', width: 180, title: '修改人'},
                    {field: 'updateDate', width: 180, title: '修改时间'},
                    {field: 'enableStatus', width: 80, title: '状态',
                        templet: function (row) {
                            if(row.enableStatus == "1"){
                                return "启用"
                            }
                            return "禁用"
                        }},
                    {title: '操作', minWidth: 350, toolbar: '#roleTableBar', align: "center"}
                ]
            ],
            limits: [15,30,100,200],
            limit: 15,
            page: true,
            skin: 'line'
        });

        // 监听搜索操作
        form.on('submit(data-search-btn)', function (data) {
            //执行搜索重载
            table.reload('roleTable', {
                page: {
                    curr: 1
                }
                , where: data.field
            }, 'data');

            return false;
        });

        /**
         * toolbar监听事件
         */
        table.on('toolbar(roleTableFilter)', function (obj) {
            if (obj.event === 'add') {  // 监听添加操作
                var index = layer.open({
                    title: '添加角色',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,

                    area: ['100%', '100%'],
                    content: "[[@{/role/addPage}]]"
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
            } else if (obj.event === 'delete') {  // 监听删除操作
                var checkStatus = table.checkStatus('roleTable')
                    , data = checkStatus.data;
                if(data==null||data.length<=0)
                {
                    layer.msg("请选择要操作的记录");
                    return;
                }
                layer.confirm('确定删除角色?', function (index) {
                    $.ajax({
                        url:"[[@{/}]]role/delete/ids",
                        contentType: "application/json; charset=utf-8",
                        type:'DELETE',
                        data:JSON.stringify(data),
                        success:function(data){
                            layer.msg(data.msg);

                            //执行搜索重载
                            table.reload('roleTable', {
                                page: {
                                    curr: 1
                                }
                                , where: data.field
                            }, 'data');

                        },
                        complete:function(data)
                        {
                            layer.close(index);
                        }
                    });
                });
            }
        });


        /**
         * 拿到这次选择的所有子节点(所有层级)
         * @param currentNode
         * @param childNodes
         * @param selectNodes
         */
        function querySelectNodeChildArray(currentNode,childNodes,selectNodes)
        {
            for(var i=0;i<selectNodes.length;i++)
            {
                var node = selectNodes[i];
                if(node.pid==currentNode.id)
                {
                    childNodes.push(node);
                    //纵向递归
                    querySelectNodeChildArray(node,childNodes,selectNodes);
                }
            }
        }
        /**
         * 拿到这次选择的所有子节点(所有层级)
         * @param currentNode
         * @param childNodes
         * @param treeDateCache
         */
        function querySelectCacheNodeChildArray(currentNode,childCacheNodes,treeDateCache)
        {
            for(var i=0;i<treeDateCache.length;i++)
            {
                var node = treeDateCache[i];
                if(node.pid==currentNode.id)
                {
                    childCacheNodes.push(node);
                    //纵向递归
                    querySelectCacheNodeChildArray(node,childCacheNodes,treeDateCache);
                }
            }
        }

        //重新设置半选和全选状态
        function setHalfCheck(selectNode,selectNodes)
        {
            var pushTree={id:selectNode.id,pid:selectNode.pid,functionId:selectNode.functionId,halfCheck:false,name:selectNode.name};
            var childNodes = new Array();
            var childCacheNodes = new Array();
            //拿到这次选择的所有子节点(所有层级)
            querySelectNodeChildArray(selectNode,childNodes,selectNodes);

            //查询出缓存中的所有子节点(所有层级)
            querySelectCacheNodeChildArray(selectNode,childCacheNodes,allTreeDataArray);


            if(childNodes.length>0||childCacheNodes.length>0)
            {
                //子节点全选
                if(childNodes.length==childCacheNodes.length)
                {
                    pushTree.halfCheck=false;
                }else{
                    pushTree.halfCheck=true;
                }
            }else{
                //如果没有展开这个节点,这时候缓存没有这个节点信息,就读取返回的的选中状态
                pushTree.halfCheck = selectNode.halfCheck;
            }
            pushTreeDataArray.push(pushTree);

        }

        function filter(treeId, parentNode, data) {
            if(data.data!=null&&data.data.length>0) {
                for (var i = 0; i < data.data.length; i++) {
                    allTreeDataArray.push(data.data[i]);
                }
            }
            return data.data;
        }

        //监听表格复选框选择
        table.on('checkbox(roleTableFilter)', function (obj) {
        });

        function zTreeOnCheck(event, treeId, treeNode) {
            treeNode.halfCheck=false;
            zTreeObj.updateNode(treeNode);
        };

        table.on('tool(roleTableFilter)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') {

                var index = layer.open({
                    title: '编辑角色',
                    type: 2,
                    shade: 0.2,
                    maxmin:true,

                    area: ['100%', '100%'],
                    content: '[[@{/}]]role/editPage/'+data.id
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });
                return false;
            } else if (obj.event === 'delete') {
                layer.confirm('确定删除该角色?', function (index) {
                    $.ajax({
                        url:"[[@{/}]]role/delete/"+data.id,
                        contentType: "application/json; charset=utf-8",
                        type:'DELETE',
                        success:function(data){
                            layer.msg(data.msg);

                            //执行搜索重载
                            table.reload('roleTable', {
                                page: {
                                    curr: 1
                                }
                                , where: data.field
                            }, 'data');

                        },
                        complete:function(data)
                        {
                            layer.close(index);
                        }
                    });
                });
            } else if (obj.event === 'permission') {
                var roleId = data.roleId;
                var appCode= data.appCode;
                index = layer.open({
                    title: '选择权限',
                    type: 1,
                    shade: 0.2,
                    maxmin:true,

                    area: ['20%', '60%'],
                    btn: ['确定'],
                    content: "<ul id=\"permissionTree\" style='height:90%' class=\"ztree\"></ul>",
                    success:function(layero){
                        //清空节点缓存
                        if(allTreeDataArray.length>0) {
                            allTreeDataArray.splice(0, allTreeDataArray.length);
                        }
                        //清空要保存的节点数组
                        if(pushTreeDataArray.length>0)
                        {
                            pushTreeDataArray.splice(0, pushTreeDataArray.length);
                        }
                        loadding = layer.load();

                        var setting = {
                            async: {
                                enable: true,
                                url:"[[@{/}]]function/query/role/function/tree/"+appCode+"/"+roleId,
                                autoParam:["id", "pid", "name"],
                                dataFilter: filter
                            },
                            check: {
                                enable: true
                            },
                            data:{
                                simpleData:{
                                    enable: true,
                                    idKey:'id',
                                    pIdKey:'pid',
                                    rootPId: -1
                                }
                            },
                            callback: {
                                onCheck: zTreeOnCheck
                            },
                            view:{
                                showIcon: true
                            }
                        };

                        $.ajax({
                            url:"[[@{/}]]function/query/role/function/tree/"+appCode+"/"+roleId,
                            type:"POST",
                            dataType: "json",
                            success: function(data){
                                if(data.data!=null) {
                                    for (var i = 0; i < data.data.length; i++) {
                                        allTreeDataArray.push(data.data[i]);
                                    }
                                }
                                zTreeObj = $.fn.zTree.init($("#permissionTree"),setting, data.data);
                            },
                            error: function(){

                            },
                            complete:function()
                            {
                                layer.close(loadding);
                            }
                        });


                    },
                    yes: function(index, layero){
                        var checkedNodes = zTreeObj.getCheckedNodes();
                        if(checkedNodes==null||checkedNodes.length<=0)
                        {
                            layer.msg("请选择权限");
                            return false;
                        }

                        savePermissionLoadding = layer.load();

                        //清空要保存的节点数组
                        if(pushTreeDataArray.length>0)
                        {
                            pushTreeDataArray.splice(0, pushTreeDataArray.length);
                        }

                        for(var i=0;i<checkedNodes.length;i++)
                        {
                            //设置半选 全选状态
                            setHalfCheck(checkedNodes[i],checkedNodes);
                        }

                        $.ajax({
                            url: "[[@{/}]]role/connect/functions",
                            contentType: "application/json; charset=utf-8",
                            type: 'POST',
                            data: JSON.stringify({functions:pushTreeDataArray,roleId: data.roleId, appCode: data.appCode}),
                            success: function (data) {
                                if (data.code == 0) {
                                    layer.msg(data.msg);
                                    return false;
                                }
                                layer.close(index);
                            },
                            complete:function()
                            {
                                layer.close(savePermissionLoadding);
                            }
                        });
                    }
                });
                $(window).on("resize", function () {
                    layer.full(index);
                });


            }
        });

    });
</script>


<script type="text/javascript" th:src="@{/lib/zTree/js/jquery.ztree.core.js}"></script>
<script type="text/javascript" th:src="@{/lib/zTree/js/jquery.ztree.excheck.js}"></script>
<script type="text/javascript" th:src="@{/lib/zTree/js/jquery.ztree.exedit.js}"></script>

</body>
</html>